﻿using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using PoolGame2.Physics;

namespace PoolGame2.Game
{
    class Scene : GameObject
    {

        public Scene(PoolGame game)
            : base(game)
        {
        }

        public override void Draw(Microsoft.Xna.Framework.GameTime gametime)
        {
            if (visible == false)
                return;

            if (modelObject != null)
            {
                Model model = modelObject.getModel();
                // Copy any parent transforms.
                Matrix[] transforms = new Matrix[model.Bones.Count];
                model.CopyAbsoluteBoneTransformsTo(transforms);

                Matrix worldMatrix = getWorldMatrix();

                if (this.getPhysicsObject() != null)
                {
                    PhysicsObject physicsObject = this.getPhysicsObject();
                    if (!physicsObject.getVisible())
                        return;
                    Vector3 pos = physicsObject.getPosition();

                    worldMatrix = Matrix.Identity;

                    if (physicsObject is Ball)
                        worldMatrix *= ((Ball)physicsObject).getOrientation();

                    worldMatrix *= Matrix.CreateTranslation(pos);

                }

                PoolGame game = (PoolGame)this.Game;
                foreach (ModelMesh mesh in modelObject.getModel().Meshes)
                {
                    foreach (BasicEffect effect in mesh.Effects)
                    {
                        effect.EnableDefaultLighting();
                        effect.PreferPerPixelLighting = true;
                        effect.DirectionalLight0.Direction = Vector3.Down;
                        effect.DirectionalLight0.DiffuseColor = new Vector3(1.0f, 1.0f, 1.0f);
                        effect.AmbientLightColor = new Vector3(0.7f, 0.6f, 0.6f);
                        effect.DirectionalLight0.Enabled = true;
                        effect.World = transforms[mesh.ParentBone.Index] * worldMatrix;
                        effect.Projection = game.gameManager.GetCameraManager().GetCamera().projectionMatrix;
                        effect.View = game.gameManager.GetCameraManager().GetCamera().viewMatrix;
                    }
                    mesh.Draw();
                }
            }

            foreach (GameObject child in childrenObjects)
            {
                child.Draw(gametime);
            }
        }
    }
}
